<?php
namespace app\index\controller\dictionary;
use app\index\controller\BaseIndex;
use szktor\ClinicDict; //诊所门店公共字典
use app\common\model\ClinicDictsheet; //字典表数据

/*
* 前台-字典维护 -> 厂商管理
* index/dictionary.manufacturer/index
*/
class Manufacturer extends BaseIndex
{
    protected $noNeedLogin = [];  //无需登录的方法，同时也就不需要鉴权了
    protected $noNeedRight = ['info','del','find_manufacturer']; //无需鉴权的方法，但需要登录

    //首页
    public function index()
    {
        if($this->request->isPost() || $this->request->isAjax())
        {
            try
            {
                $post = $this->request->only(['dicttype','cp_type','keyword','status','page'],'post');
                if(!isset($post['dicttype']))
                {
                    return json(['code' => '1', 'msg' => '参数错误，无法获取数据', 'count' => '0', 'data' => []]);
                }
                $post['dicttype'] = strtolower($post['dicttype']);
                $post['cp_type'] = strtolower($post['cp_type']);
                //条件
                $map = [['clinic_id','=', $this->admin['clinic_id']]];
                $page = isset($post['page']) ? $post['page'] : 1;
                if(isset($post['dicttype']) && $post['dicttype'] != '')
                {
                    if($post['dicttype'] != 'all') $map[] = ['cs_type','=',$post['dicttype']];
                }
                if(isset($post['cp_type']) && $post['cp_type'] != '')
                {
                    if($post['cp_type'] != 'all') $map[] = ['cp_type','=',$post['cp_type']];
                }
                if(isset($post['keyword']) && $post['keyword'] != '')
                {
                    $map[] = ['name|short_name|bianma|py_code|wb_code','like','%' . $post['keyword'] . '%'];
                }
                if(isset($post['status']) && $post['status'] != '')
                {
                    if(strtoupper($post['status']) != 'ALL') $map[] = ['status','=',(int)$post['status']];
                }
                $limit = intval($this->pageNum) > 0 ? intval($this->pageNum) : 20;
                $list = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_manufacturer')->where($map)->field('*')
                        ->order('id desc')->paginate($limit,false,['page' => $page, 'var_page' => 'page']);
                if (count($list) <= 0) {
                    return json(['code' => '1', 'msg' => '当前页下的数据已显示完毕！', 'count' => '0', 'data' => []]);
                }
                $res = ['code' => 0,'msg' => '', 'count' => $list->total(), 'data' => $list->items()];
                //厂商供应的产品分类列表
                $cscpArr = ClinicDict::getChangShangProductCateList();
                foreach ($res['data'] as $key => &$val) {
                    $val['cp_type_txt'] = _getDictNameTxt($val['cp_type'],$cscpArr);
                    $val['create_time'] = $val['create_time'] > 0 ? date('Y-m-d H:i:s',$val['create_time']) : '';
                    $val['address_text'] = '[' . $val['country'] . ']' . $val['province'] . $val['city']. $val['address'];
                }
                return json($res);
            }catch (\think\Exception $e){ // use think\Exception;
               return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
            }
        }
		$this->assign([
            'cs_type_list' => ClinicDict::getChangShangCateList(), //厂商类型列表
            'cscp_type_list' => ClinicDict::getChangShangProductCateList(), //厂商供应的产品分类列表
        ]);
        return $this->view->fetch();
    }
    //修改 + 新增
    public function info()
    {
        if(!$this->request->isAjax())
        {
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
        }
        $data = $this->request->only([
            'dicttype','id','name','short_name','bianma','cs_type','cp_type','zhizhao_no','py_code','wb_code',
            'tel','country','province','city','address','remarks','status',
            'jyxk_no','gsp_no','ylqx_no','ylqx_no1','ylqx_no2','cpjybg_no','cpjybg_no1','cpjybg_no2',
        ],'post');
        if(!isset($data['id']))
        {
            return json(['err' => '1', 'msg' => '参数错误，无法执行']);
        }
        $dictType = strtolower($data['dicttype']);
        if(!isset($data['name']) || $data['name'] == '')
        {
            return json(['err' => '2', 'msg' => '必须输入一个名称']);
        }
        unset($data['dicttype']);
        try
        {
            $info = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_manufacturer')->where(['id' => intval($data['id']), 'clinic_id' => $this->admin['clinic_id']])->find();
            if($info) //数据已存在
            {
                unset($data['id']);
                $editRes = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_manufacturer')->where(['id' => $info['id']])->update($data);
            }else{ //数据不存在
                unset($data['id']);
                $sqlData = array_merge($data,[
                    'clinic_id' => $this->admin['clinic_id'], //诊所门店表的id
                    'create_time' => time(), //创建时间
                ]);
                $editRes = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_manufacturer')->insertGetId($sqlData);
            }
            unset($info,$data);
            if(!$editRes) return json(['err' => '2', 'msg' => '厂商数据保存失败']);
            return json(['err' => '0', 'msg' => '厂商数据已保存成功']);
        }catch (\think\Exception $e){ // use think\Exception;
           return json(['err' => '500', 'msg' => '失败：' . $e->getMessage()]);
        }
    }
    //删除
    public function del()
    {
        if(!$this->request->isAjax())
        {
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
        }
        try
        {
            $data = $this->request->only(['dicttype','id'],'post');
            if(!isset($data['dicttype']))
            {
                return json(['err' => '1', 'msg' => '参数错误，无法执行']);
            }
            $r = false;
            $map = [['id','in',$data['id']],['clinic_id','=',$this->admin['clinic_id']]];
            //字典表数据_通用
            $r = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_manufacturer')->where($map)->delete();
            if(!$r) return json(['err' => '2', 'msg' => '删除失败，请重试']);
            return json(['err' => '0', 'msg' => '删除成功']);
        }catch (\think\Exception $e){ // use think\Exception;
           return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
        }
    }

    //搜索添加厂家 index/dictionary.manufacturer/find_manufacturer
    public function find_manufacturer()
    {
        if(!$this->request->isAjax())
        {
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
        }
        try
        {
            $data = $this->request->only(['keyword','limit','page'],'post');
            if(!isset($data['page']))
            {
                return json(['err' => '2', 'msg' => '参数错误，无法获取数据']);
            }
            //条件
            $map = [['clinic_id','=', $this->admin['clinic_id']],['status','=','1']];
            if(isset($data['keyword']) && $data['keyword'] != '')
            {
                $map[] = ['name|bianma|py_code|wb_code|tel','like','%' . $data['keyword'] . '%'];
            }
            $limit = intval($data['limit']) > 0 ? intval($data['limit']) : 20;
            $field = 'id,name,short_name,bianma,cs_type,cp_type,py_code,wb_code,tel';
            $list = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_manufacturer')->where($map)->field($field)
                    ->order('id desc')->paginate($limit,false,['page' => $data['page'], 'var_page' => 'page']);
            if (count($list) <= 0) {
                return json(['err' => '3', 'msg' => '当前页下无数据']);
            }
            $res = ['err' => '0', 'page' => $data['page'], 'limit' => $limit, 'data' => $list->items()];
            //厂商类型列表
            $csTypeArr = ClinicDict::getChangShangCateList();
            //厂商供应的产品分类列表
            $cscpArr = ClinicDict::getChangShangProductCateList();
            foreach ($res['data'] as $key => &$val) {
                $val['cs_type_txt'] = _getDictNameTxt($val['cs_type'],$csTypeArr); //厂商类型列表
                $val['cp_type_txt'] = _getDictNameTxt($val['cp_type'],$cscpArr); //厂商供应的 产品 分类列表
            }
            return json($res);
        }catch (\think\Exception $e){ // use think\Exception;
           return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
        }
    }
}
